<template>
  <li class="todo" :class="{ editing: isEdit }">
    <div class="view">
      <!-- 是否完成 -->
      <input
        class="toggle"
        type="checkbox"
        :checked="completed"
        @change="handleChange"
      />

      <label @dblclick="showEdit">{{ title }}</label>
      <button class="destroy" @click="delTodo(id)"></button>
    </div>

    <input
      ref="editInput"
      class="edit"
      type="text"
      :value="title"
      @keyup.enter="handleEdit"
      @blur="setCurEditId(0)"
    />
  </li>
</template>

<script>
import { mapActions, mapMutations, mapState } from "vuex";

export default {
  props: {
    id: Number,
    title: String,
    completed: Boolean,
  },

  computed: {
    ...mapState(["curEditId"]),
    isEdit() {
      return this.curEditId === this.id;
    },
  },

  methods: {
    ...mapMutations(["setCurEditId"]),
    ...mapActions(["delTodo"]),

    showEdit() {
      this.setCurEditId(this.id);

      this.$nextTick(() => {
        this.$refs.editInput.focus();
      });
    },

    handleEdit(event) {
      console.log("handleEdit", event.target.value);

      // 1. 获取最新输入框 value
      const value = event.target.value;

      // 2. 派发 updateTodo 动作
      this.$store.dispatch("updateTodo", {
        id: this.id,
        title: value,
        completed: this.completed,
      });
    },

    handleChange(event) {
      const checked = event.target.checked;
      console.log("checked", checked);

      this.$store.dispatch("updateTodo", {
        id: this.id,
        title: this.title,
        completed: checked,
      });
    },
  },
};
</script>
